package me.pppploi8.webmcs.main.urlmapping;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import java.util.UUID;

import org.quartz.CronScheduleBuilder;

import me.pppploi8.webmcs.http.jetty.HttpUrlMapping;
import me.pppploi8.webmcs.task.TaskCore;
import me.pppploi8.webmcs.task.TaskManage;
import me.pppploi8.webmcs.task.TaskManageFactory;

public class WebmcsTaskService extends HttpUrlMapping{
	private TaskManage tm;
	
	public WebmcsTaskService(){
		this.tm = TaskManageFactory.getTaskManage();
	}
	
	public String addtask(){
		Map<String,String> map = new TreeMap<String,String>();
		map.put("exectype", getRequest().getParameter("exectype"));
		map.put("type", getRequest().getParameter("type"));
		map.put("time", getRequest().getParameter("time"));
		map.put("content", getRequest().getParameter("content"));
		//合法性校验
		try{
			int num = Integer.parseInt(map.get("exectype"));
			if (num<0 || num>2)
				return "{\"status\":false,\"msg\":\"PARAMERROR\"}";
			num = Integer.parseInt(map.get("type"));
			if (num<0 || num>3)
				return "{\"status\":false,\"msg\":\"PARAMERROR\"}";
			if (num == 1){
				num = Integer.parseInt(map.get("content"));
				if (num<0 || num>4)
					return "{\"status\":false,\"msg\":\"PARAMERROR\"}";
			}
			// Cron表达式合法校验
			CronScheduleBuilder.cronSchedule(map.get("time")).build();
		}catch(Exception e){
			return "{\"status\":false,\"msg\":\"PARAMERROR\"}";
		}
		tm.addTask(tm.createTask(UUID.randomUUID().toString(), map),true);
		return "{\"status\":true}";
	}
	public String deltask(){
		if(tm.removeTask(getRequest().getParameter("id")))
			return "{\"status\":true}";
		return "{\"status\":false,\"msg\":\"IDERROR\"}";
	}
	public Object gettasks(){
		Map<String,Object> map = new TreeMap<>();
		List<String[]> list = new ArrayList<>();
		map.put("status", true);
		Map<String,TaskCore> tasks = tm.getTasks();
		for(Entry<String, TaskCore> e : tasks.entrySet()){
			String[] s = new String[5];
			s[0] = e.getKey();
			s[1] = e.getValue().getType() + "";
			s[2] = e.getValue().getContent();
			s[3] = e.getValue().getTime() + "";
			s[4] = e.getValue().getExecType();
			list.add(s);
		}
		map.put("list", list);
		return map;
	}
}
